/**
 * 
 */
package org.demetra.jets.bdb;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.demetra.core.JetsException;
import org.demetra.core.JetsService;

import com.ericsson.otp.erlang.OtpErlangBinary;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangTuple;
import com.ericsson.otp.erlang.OtpOutputStream;
import com.sleepycat.bind.serial.ClassCatalog;
import com.sleepycat.bind.serial.SerialSerialKeyCreator;

/**
 * @author vvorobyov
 *
 */
public class OtpErlangTupleSecondaryKeyCreator extends SerialSerialKeyCreator {

	private int _elemPos;

	public OtpErlangTupleSecondaryKeyCreator(
			ClassCatalog classCatalog,
			int aElemPos) {
		super(classCatalog, OtpErlangObject.class, OtpErlangTuple.class, OtpErlangObject.class);
		_elemPos = aElemPos;
	}

	@Override
	public Object createSecondaryKey(Object arg0, Object arg1) {
		OtpErlangTuple tuple =  (OtpErlangTuple)arg1;
		return md5OfOtpErlangObject(tuple.elementAt(_elemPos));
	}
	
	public static final OtpErlangBinary md5OfOtpErlangObject(OtpErlangObject aObj)
	{
		byte[] binRep=new OtpOutputStream(aObj).toByteArray();
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new JetsException(e);
		}
		md5.update(binRep);
		return new OtpErlangBinary(md5.digest());
	}

}
